package com.dwxt.parabolic.service;

import com.dwxt.common.base.BaseResult;
import com.dwxt.common.base.Page;
import com.dwxt.common.base.StatusCode;
import com.dwxt.common.base.YesOrNo;
import com.dwxt.common.util.IDUtils;
import com.dwxt.common.util.MD5Utils;
import com.dwxt.parabolic.base.LevelType;
import com.dwxt.parabolic.base.QuantityType;
import com.dwxt.parabolic.base.RoleType;
import com.dwxt.parabolic.dao.*;
import com.dwxt.parabolic.entity.*;
import com.dwxt.parabolic.utils.RedisUtil;
import com.dwxt.parabolic.utils.RequestUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CompanyService {
    @Autowired
    private CompanyMapper companyMapper;

    @Autowired
    private AreaMapper areaMapper;

    @Autowired
    private InstallCompanyService installCompanyService;

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private UserService userService;

    public BaseResult getCompanyList(Page page, Company company, String parentId) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        CompanyExample example = new CompanyExample();
        example.setOrderByClause("create_time desc");
        CompanyExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(company.getName())) {
            criteria.andNameLike("%" + company.getName() + "%");
        }
        if (company.getStatus() != null) {
            criteria.andStatusEqualTo(company.getStatus());
        }
        if (StringUtils.isNotBlank(parentId)) {
            Area area = areaMapper.selectByPrimaryKey(parentId);
            if (area.getLevelType() == LevelType.ONE.getLevel()) {
                criteria.andProvinceIdEqualTo(parentId);
            } else if (area.getLevelType() == LevelType.TWO.getLevel()) {
                criteria.andCityIdEqualTo(parentId);
            } else {
                criteria.andAreaIdEqualTo(parentId);
            }
        }
        //所属那个安装公司
        criteria.andInstallCompanyIdEqualTo(RequestUtil.getCurrentCompanyId());
        List<Company> companyList = companyMapper.selectByExample(example);
        PageInfo pageInfo = new PageInfo(companyList);
        List<Company> collect = companyList.stream().map(company1 -> {
            User user = userService.selectByPrimaryKey(company1.getUserId());
            company1.setUserName(user.getUserName());
            company1.setPhoneNumber(user.getPhoneNumber());
            InstallCompany installCompany = installCompanyService.selectByPrimaryKey(company1.getInstallCompanyId());
            company1.setInstallCompanyName(installCompany.getName());
            company1.setInstallCompanyLogo(installCompany.getLogo());
            User installUser = userService.selectByPrimaryKey(company1.getInstallUserId());
            company1.setInstallUserPhoneNumber(installUser.getPhoneNumber());
            company1.setInstallUserName(installUser.getUserName());
            return company1;
        }).collect(Collectors.toList());
        pageInfo.setList(collect);
        return BaseResult.ok(pageInfo);
    }

    @Transactional
    public BaseResult add(Company company, String code) {
        /*String redisCode = RedisUtil.get(company.getPhoneNumber(), String.class);
        if (!code.equalsIgnoreCase(redisCode)) {
            return BaseResult.build(StatusCode.SMS_CODE_ERROR);
        }*/

        User user = userService.selectByPhone(company.getPhoneNumber());
        if (user != null) {
            return BaseResult.build(StatusCode.PHONE_EXIST);
        }
        company.setId(IDUtils.genItemId());

        //插入用户信息（负责人信息）
        user = User.builder().id(IDUtils.genItemId()).companyId(company.getId()).isManager(YesOrNo.YES)
                .password(MD5Utils.MD5Encode("123456")).phoneNumber(company.getPhoneNumber())
                .roleId("3").userName(company.getUserName()).build();
        userService.insertSelective(user);

        //插入公司数据
        Area area = areaMapper.selectByPrimaryKey(company.getAreaId());
        Area city = areaMapper.selectByPrimaryKey(company.getCityId());
        Area province = areaMapper.selectByPrimaryKey(company.getProvinceId());
        //可以考虑从header 中取
        InstallCompany installCompany = installCompanyService.selectByPrimaryKey(company.getInstallCompanyId());
        User installUser = userService.selectByPrimaryKey(company.getInstallUserId());
        company.setUserId(user.getId());
        company.setAreaName(area.getName());
        company.setCityName(city.getName());
        company.setProvinceName(province.getName());
        company.setInstallCompanyLogo(installCompany.getLogo());
        company.setInstallCompanyName(installCompany.getName());
        company.setInstallUserName(installUser.getUserName());
        company.setInstallUserPhoneNumber(installUser.getPhoneNumber());
        companyMapper.insertSelective(company);


        //更改安装公司数量
        installCompanyService.addByQuantityType(company.getInstallCompanyId(), QuantityType.company, 1);
        return BaseResult.ok();
    }

    public BaseResult update(Company company) {
        companyMapper.updateByPrimaryKeySelective(company);
        return BaseResult.ok();
    }

    @Transactional
    public BaseResult delete(String id) {
        Company company = companyMapper.selectByPrimaryKey(id);
        companyMapper.deleteByPrimaryKey(id);
        userService.deleteByCompanyId(id);
        installCompanyService.addByQuantityType(company.getInstallCompanyId(), QuantityType.company, -1);
        return BaseResult.ok();
    }

    /**
     * 根据type,增加相应的数量
     *
     * @param companyId
     * @param type
     * @param count
     */
    public void addByQuantityType(String companyId, QuantityType type, int count) {
        Company company = companyMapper.selectByPrimaryKey(companyId);
        if (type.equals(QuantityType.user)) {
            company.setUserCount(company.getUserCount() + count);
        }
        if (type.equals(QuantityType.device)) {
            company.setDeviceCount(company.getDeviceCount() + count);
        }
        if (type.equals(QuantityType.ipc)) {
            company.setIpcCount(company.getIpcCount() + count);
        }
        companyMapper.updateByPrimaryKeySelective(company);
    }

    public Company selectByPrimaryKey(String companyId) {
        return companyMapper.selectByPrimaryKey(companyId);
    }

    public BaseResult selectByInstallCompanyId() {
        return BaseResult.ok(selectByInstallCompanyId(RequestUtil.getCurrentCompanyId()));
    }

    public List<Company> selectByInstallCompanyId(String installCompanyId) {
        CompanyExample example = new CompanyExample();
        if (!"0".equals(installCompanyId)) {
            example.createCriteria().andInstallCompanyIdEqualTo(installCompanyId);
        }
        return companyMapper.selectByExample(example);
    }

    public BaseResult current() {
        if (RoleType.COMPANY.getType().equals(RequestUtil.getCurrentUserType())) {
            Company company = companyMapper.selectByPrimaryKey(RequestUtil.getCurrentCompanyId());
            return BaseResult.ok(company);
        }
        return BaseResult.build(StatusCode.PARAMETER_WRONG);
    }

    public void updateByPrimaryKeySelective(Company company) {
        companyMapper.updateByPrimaryKeySelective(company);
    }

    @Transactional
    public BaseResult startOrEnd(String id) {
        Company company = companyMapper.selectByPrimaryKey(id);
        if (company.getStatus() == YesOrNo.YES) {
            userService.updateByCompanyId(id, YesOrNo.NO);
            deviceService.endByCompanyId(id);
            company.setStatus(YesOrNo.NO);
            updateByPrimaryKeySelective(company);
        } else {
            userService.updateByCompanyId(id, YesOrNo.YES);
            company.setStatus(YesOrNo.YES);
            updateByPrimaryKeySelective(company);
        }
        return BaseResult.ok();
    }
}
